package com.cxz.kotlin.baselibs.utils;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fphoenixcorneae.util.toast.ToastUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.CASE_INSENSITIVE;
import static java.util.regex.Pattern.UNICODE_CASE;
import static java.util.regex.Pattern.compile;

public class UiUtils {

    //base64转图片
    public static Bitmap base64toBitmap(String string) {
        //将字符串转换成Bitmap类型
        byte[] decodedString = Base64.decode(string.split(",")[1], Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
        return bitmap;
    }

    public static void setGrayColorFilter(ImageView imageView) {
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0); // 设置饱和度
        ColorMatrixColorFilter grayColorFilter = new ColorMatrixColorFilter(cm);
        imageView.setColorFilter(grayColorFilter); // 如果想恢复彩色显示，设置为null即可
    }


    public static void setViewWideHeightWithinChange(Context context, View view, int width, int height) {
        //取控件当前的布局参数
        ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) view.getLayoutParams();
        //设置宽度值
        params.width = width;
        //设置高度值
        params.height = height;
        //使设置好的布局参数应用到控件
        view.setLayoutParams(params);
    }

    public static void setViewWideHeight(Context context, View view, float width, float height) {
        //取控件当前的布局参数
        ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) view.getLayoutParams();
        //设置宽度值
        params.width = DensityUtil.dip2px(context, width);
        //设置高度值
        params.height = DensityUtil.dip2px(context, height);
        //使设置好的布局参数应用到控件
        view.setLayoutParams(params);
    }

    public static void setViewHeight(Context context, View view, float height) {
        LogUtil.d("setViewHeight", "height:" + height);
        //取控件当前的布局参数
        ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) view.getLayoutParams();
        //设置高度值
        params.height = (int) height;
        //使设置好的布局参数应用到控件
        view.setLayoutParams(params);
    }

    public static void setViewHeightWrapContent(Context context, View view) {
        //取控件当前的布局参数
        ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) view.getLayoutParams();
        //设置高度值
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        //使设置好的布局参数应用到控件
        view.setLayoutParams(params);
    }


    public static Bitmap drawable2Bitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        } else if (drawable instanceof NinePatchDrawable) {
            Bitmap bitmap = Bitmap
                    .createBitmap(
                            drawable.getIntrinsicWidth(),
                            drawable.getIntrinsicHeight(),
                            drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                                    : Bitmap.Config.RGB_565);
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight());
            drawable.draw(canvas);
            return bitmap;
        } else {
            return null;
        }
    }

    /**
     * 修改Toolbar的渐变度
     */
    public static int changeAlpha(int color, float fraction) {
        int red = Color.red(color);
        int green = Color.green(color);
        int blue = Color.blue(color);
        int alpha = (int) (Color.alpha(color) * fraction);
        return Color.argb(alpha, red, green, blue);
    }

    /**
     * 根据宽度设置textview大小
     *
     * @param tv
     * @param maxWidth
     * @param text
     * @return
     */
    public static float adjustTvTextSize(TextView tv, int maxWidth, String text) {
        tv.setText(text);
        int avaiWidth = maxWidth - tv.getPaddingLeft() - tv.getPaddingRight() - 10;

        if (avaiWidth <= 0 || TextUtils.isEmpty(text)) {
            return tv.getPaint().getTextSize();
        }

        TextPaint textPaintClone = new TextPaint(tv.getPaint());
        // note that Paint text size works in px not sp
        float trySize = textPaintClone.getTextSize();

        while (textPaintClone.measureText(text) > avaiWidth) {
            trySize--;
            textPaintClone.setTextSize(trySize);
        }

        tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, trySize);
        return trySize;
    }


    public static void setMarginTop(View v, int t) {
        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(0, t, 0, 0);
            v.requestLayout();
        }
    }

    public static void setMargin(View v, int l, int t, int r, int b) {
        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(l, t, r, b);
            v.requestLayout();
        }
    }

    public static void setMarginTopRight(View v, int t, int r) {
        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(0, t, r, 0);
            v.requestLayout();
        }
    }

    public static void setMarginRight(View v, int r) {
        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(0, 0, r, 0);
            v.requestLayout();
        }
    }

    public static void setMarginBottom(View v, int b) {
        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(0, 0, 0, b);
            v.requestLayout();
        }
    }

    public static ImageView getImageView(Activity activity, int widthHeight, int marginRight) {
        ImageView iv = new ImageView(activity);
        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(DensityUtil.dp2px(activity, widthHeight), DensityUtil.dp2px(activity, widthHeight));
        p.setMarginEnd(DensityUtil.dp2px(activity, marginRight));
        p.topMargin = DensityUtil.dp2px(activity, marginRight);
        iv.setLayoutParams(p);
        iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
        return iv;
    }


    public static void copyText(Context activity, String data) {
        ClipboardManager mClipBorad = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData text = ClipData.newPlainText("text", data);
        mClipBorad.setPrimaryClip(text);
        ToastUtil.INSTANCE.show("复制成功");
    }

    public static void setEtNumLetterLimit(final EditText mEtPwd) {
        mEtPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String editable = mEtPwd.getText().toString();
                String regEx = "[^a-zA-Z0-9]";  //只能输入字母或数字
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(editable);
                String str = m.replaceAll("").trim();    //删掉不是字母或数字的字符
                if (!editable.equals(str)) {
                    mEtPwd.setText(str);  //设置EditText的字符
                    mEtPwd.setSelection(str.length()); //因为删除了字符，要重写设置新的光标所在位置
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    public static Bitmap loadBitmapFromView(View v) {
        if (v == null) {
            return null;
        }
        Bitmap screenshot;
        screenshot = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(screenshot);
        c.translate(-v.getScrollX(), -v.getScrollY());
        v.draw(c);
        return screenshot;
    }


    private static final String IMAGE_FILE_NAME_TEMPLATE = "Image%s.jpg";
    private static final String IMAGE_FILE_PATH_TEMPLATE = "%s/%s";

    /**
     * 存储到sdcard
     *
     * @param bmp
     * @param maxSize  为0不压缩
     * @param mContext
     * @return
     */
    public static String saveToSD(Bitmap bmp, int maxSize, Context mContext) {
        if (bmp == null) {
            return "";
        }
        //判断sd卡是否存在
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //文件名
            long systemTime = System.currentTimeMillis();
            String imageDate = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date(systemTime));
            String mFileName = String.format(IMAGE_FILE_NAME_TEMPLATE, imageDate);
            //文件全名

            File externalStoragePublicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
            String mstrRootPath = externalStoragePublicDirectory.getPath();
            String filePath = String.format(IMAGE_FILE_PATH_TEMPLATE, mstrRootPath, mFileName);
            File file = new File(filePath);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                compressAndGenImage(bmp, filePath, maxSize, mContext);
                MediaStore.Images.Media.insertImage(mContext.getContentResolver(), bmp, mFileName, null);
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(file);
                intent.setData(uri);
                mContext.sendBroadcast(intent);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                bmp.recycle();
            }


            return filePath;
        }
        return "";
    }

    public static String createImagePath() {
        //判断sd卡是否存在
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //文件名
            long systemTime = System.currentTimeMillis();
            String imageDate = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date(systemTime));
            String mFileName = String.format(IMAGE_FILE_NAME_TEMPLATE, imageDate);

            //文件全名
            File externalStoragePublicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
            String mstrRootPath = externalStoragePublicDirectory.getPath();
//            String mstrRootPath = FileUtil.getPackageDCIMPath(AFApplication.applicationContext);
            String filePath = String.format(IMAGE_FILE_PATH_TEMPLATE, mstrRootPath, mFileName);
            File file = new File(filePath);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return filePath;
        }
        return "";
    }


    //获取某一个百分比间的颜色,radio取值[0,1]
    public static int getChangeColor(Context context, int mStartColor, int mEndColor, float radio) {

        int redStart = Color.red(mStartColor);
        int blueStart = Color.blue(mStartColor);
        int greenStart = Color.green(mStartColor);
        int redEnd = Color.red(mEndColor);
        int blueEnd = Color.blue(mEndColor);
        int greenEnd = Color.green(mEndColor);
        int red = (int) (redStart + ((redEnd - redStart) * radio + 0.5));
        int greed = (int) (greenStart + ((greenEnd - greenStart) * radio + 0.5));
        int blue = (int) (blueStart + ((blueEnd - blueStart) * radio + 0.5));
        return Color.argb(255, red, greed, blue);
    }


    public static void setMarginLeftRight(View v, int l, int r) {

        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(l, 0, r, 0);
            v.requestLayout();
        }

    }


    public void bitmapFactory(int drawable) {

    }

    /**
     * 计算出所需要压缩的大小
     *
     * @param options
     * @param reqWidth  我们期望的图片的宽，单位px
     * @param reqHeight 我们期望的图片的高，单位px
     * @return
     */
    public static int caculateSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        int sampleSize = 1;
        int picWidth = options.outWidth;
        int picHeight = options.outHeight;
        if (picWidth > reqWidth || picHeight > reqHeight) {
            int halfPicWidth = picWidth / 2;
            int halfPicHeight = picHeight / 2;
            while (halfPicWidth / sampleSize > reqWidth || halfPicHeight / sampleSize > reqHeight) {
                sampleSize *= 2;
            }
        }
        return sampleSize;
    }

    public static void compressAndGenImage(Bitmap image, String outPath, int maxSize) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // scale
        int options = 100;
        // Store the bitmap into output stream(no compress)
        image.compress(Bitmap.CompressFormat.JPEG, options, os);
        // Compress by loop
        if (maxSize != 0) {
            while (os.toByteArray().length / 1024 > maxSize) {
                // Clean up os
                os.reset();
                // interval 10
                options -= 10;
                image.compress(Bitmap.CompressFormat.JPEG, options, os);
            }
        }

        // Generate compressed image file
        FileOutputStream fos = new FileOutputStream(outPath);
        fos.write(os.toByteArray());
//        Logger.getLogger().d("compressAndGenImage--->文件大小：" + os.size()+"，压缩比例：" + options);
        fos.flush();
        fos.close();
    }

    public static void compressAndGenImage(Bitmap image, String outPath, int maxSize, Context mContext) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // scale
        int options = 70;
        // Store the bitmap into output stream(no compress)
        image.compress(Bitmap.CompressFormat.JPEG, options, os);

        // Generate compressed image file
        FileOutputStream fos = new FileOutputStream(outPath);
        fos.write(os.toByteArray());
        fos.flush();
        fos.close();
        Toast.makeText(mContext, "保存成功", Toast.LENGTH_SHORT).show();
    }

    /**
     * 禁止EditText输入空格
     *
     * @param editText
     */
    public static void setEditTextInhibitInputSpaChat(EditText editText) {
        InputFilter filterEmjo = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (isEmoji(source)) {
                    return "";
                } else {
                    return null;
                }
            }
        };
        InputFilter filterSpeChat = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
                String speChat = "[`~!@#_$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）— +|{}【】" +
                        "]";
                String speChat2 = "[-‘；：”“’。，、" +
                        "]";

                Pattern pattern = compile(speChat);
                Pattern pattern2 = compile(speChat2);
                Matcher matcher = pattern.matcher(charSequence.toString());
                Matcher matcher2 = pattern2.matcher(charSequence.toString());
                if (matcher.find() || matcher2.find()) {
                    return "";
                } else {
                    return null;
                }
            }
        };
        editText.setFilters(new InputFilter[]{filterEmjo,filterSpeChat});
    }

    public static boolean isEmoji(CharSequence string) {
        Pattern p = compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                UNICODE_CASE | CASE_INSENSITIVE);
        Matcher m = p.matcher(string);
        return m.find();
    }

    public static int getStatusBarHeight(Context context) {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }


    private static CharSequence temp;
    private static int selectionStart;
    private static int selectionEnd;

    public interface AfterTextChangedListener {
        void afterTextChanged(Editable s);
    }


    public static void setETMaxLengthAndCallBack(final EditText editText, final int MaxLeng, final TextView textView, final AfterTextChangedListener listener) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                temp = s;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                listener.afterTextChanged(s);
                if (MaxLeng != 0) {
                    selectionStart = editText.getSelectionStart();
                    selectionEnd = editText.getSelectionEnd();
                    if (temp.length() > MaxLeng) {
                        s.delete(selectionStart - 1, selectionEnd);
                        int tempSelection = selectionStart;
                        editText.setText(s);
                        editText.setSelection(tempSelection);
                    } else {
                        if (null != textView) {
                            textView.setText(temp.length() + "/"+MaxLeng);
                        }
                    }
                }
            }
        });
    }

    public static void setETMaxLength(final EditText editText, final int MaxLeng, final TextView textView) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                temp = s;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (MaxLeng != 0) {
                    selectionStart = editText.getSelectionStart();
                    selectionEnd = editText.getSelectionEnd();
                    if (temp.length() > MaxLeng) {
                        s.delete(selectionStart - 1, selectionEnd);
                        int tempSelection = selectionStart;
                        editText.setText(s);
                        editText.setSelection(tempSelection);
                    } else {
                        if (null != textView) {
                            textView.setText(temp.length() + "/"+MaxLeng);
                        }
                    }
                }
            }
        });
    }

}
